<template>
  <BasicModal v-bind="$attrs" @register="registerModal" showFooter title="新增选项" width="500px" @ok="handleSubmit">
    <BasicForm @register="registerForm" class="mr-3" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { reactive } from 'vue';
  import { FormSchema } from '@/components/Table';
  import { DefaultOptionType } from 'ant-design-vue/es/vc-select/Select';

  const emit = defineEmits(['addOption']);
  let options: DefaultOptionType[] = reactive([]);

  // 表单字段
  const formSchema: FormSchema[] = [
    {
      field: 'value',
      label: '编号',
      component: 'ApiRadioGroup',
      colProps: {
        span: 16,
      },
      required: true,
      componentProps: {
        options: options,
      },
    },
    {
      field: 'label',
      label: '选项',
      required: true,
      component: 'Input',
      colProps: {
        span: 24,
      },
    },
    {
      field: 'correct',
      label: '答案',
      component: 'RadioGroup',
      defaultValue: 1,
      colProps: {
        span: 24,
      },
      componentProps: {
        size: 'small',
        options: [
          { label: '是', value: 1 },
          { label: '否', value: 0 },
        ],
      },
    },
  ];
  // 注册表单
  const [registerForm, { resetFields, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    showActionButtonGroup: false,
    schemas: formSchema,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    // 清空
    options.splice(0, options.length);
    data.seqNos.forEach((seqNo) => options.push({ label: seqNo, value: seqNo }));
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      emit('addOption', values);
      closeModal();
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
